package service

import (
	"fmt"
	"strconv"
	"strings"
)

type SambaUser struct {
	Id   int64
	Name string
}

func GetUserList() (userList []SambaUser, err error) {
	//查询
	users, err := SendCmd(" pdbedit -L")
	if err != nil {
		return nil, err
	}
	//解释
	userList = SplitUsers(users)
	return userList, nil
}

func SplitUsers(users string) (userList []SambaUser) {
	pList := strings.Split(users, "\n")
	for _, part := range pList {
		m := strings.Split(part, ":")
		if len(m) >= 2 {
			id, _ := strconv.ParseInt(m[1], 10, 64)
			sambaUser := SambaUser{
				Id:   id,
				Name: m[0],
			}
			userList = append(userList, sambaUser)
		}
	}
	return userList
}

func AddUser(request AddUserRequest) (response string, err error) {
	//创建服务器用户
	response, err = SendCmd("useradd " + request.UserName)
	if err != nil {
		return response, err
	}

	//加入组
	response, err = SendCmd("gpasswd -a " + request.UserName + " crow")
	if err != nil {
		return response, err
	}
	//创建samba用户
	cmdString := "echo -e \"" + request.PassWord + "\\n" + request.PassWord + "\" | smbpasswd -s -a " + request.UserName
	fmt.Println(cmdString)
	//cmdString := "ls"
	response, err = SendCmd(cmdString)
	if err != nil {
		return response, err
	}
	return response, nil
}

func DeleteUser(userName string) (response string, err error) {
	response, err = SendCmd("smbpasswd -x " + userName)
	if err != nil {
		return response, err
	}
	response, err = SendCmd("userdel -r " + userName)
	if err != nil {
		return response, err
	}
	return response, nil
}
